# -*- coding: utf-8 -*-

"""
Auto Click

用PyQt5实现的定时自动点击器

author: Harry
date: 2021年10月28日
"""
import _thread
import sys
import time

import keyboard
import win32api
import win32con
from PyQt5.QtCore import *
from PyQt5.QtWidgets import (QWidget, QLabel,
                             QLineEdit, QApplication, QCheckBox)


def mouse_click():  # 模拟鼠标单击
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)


class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.app_name = 'Auto Click'
        self.version = 'V0.2'
        self.copyright = 'Copyright © 2024 Harry.'
        self.hotkey_start = 'home'

        self.set_time = 10.0  # 默认点击10s
        self.delay = 0.1
        self.task_active = False
        self.time_task_active = False
        self.init_ui()

    def init_params(self):
        # self.set_time = 10  # 默认点击10s
        self.task_active = False
        self.time_task_active = False
        self.show_time('')
        self.show_msg('')

    def init_ui(self):
        self.lbl_time = QLabel(self)
        self.lbl_time.setStyleSheet(
            "QLabel{color:rgb(225,0, 0, 75);font-size:20px;font-weight:normal;font-family:Arial Black;}")
        self.lbl_time.move(80, 20)

        self.lbl_msg = QLabel(self)
        self.lbl_msg.move(155, 28)

        self.lbl = QLabel(self)
        self.lbl.move(20, 55)
        self.lbl.setText('定时（秒）：')
        # 定时输入框
        qle = QLineEdit(self)
        qle.move(105, 55)
        qle.setText(str(self.set_time))
        qle.textChanged[str].connect(self.show_time)


        self.lbl = QLabel(self)
        self.lbl.move(20, 95)
        self.lbl.setText('间隔（秒）：')
        # 间隔输入框
        qle1 = QLineEdit(self)
        qle1.move(105, 95)
        qle1.setText(str(self.delay))
        qle1.textChanged[str].connect(self.set_delay)

        cb = QCheckBox('激活快捷键 ' + self.hotkey_start, self)
        cb.move(110, 150)
        cb.stateChanged.connect(self.start)

        self.lbl_foot = QLabel(self)
        self.lbl_foot.setStyleSheet(
            "QLabel{color:rgb(225,22,173,255);font-size:12px;font-weight:normal;font-family:Arial;}")
        self.lbl_foot.move(110, 200)
        self.lbl_foot.setText(self.copyright)

        self.setGeometry(1400, 450, 400, 220)
        self.setWindowTitle(self.app_name + self.version)
        self.show()

    def start(self, state):
        if state == Qt.Checked:
            self.setWindowTitle(self.app_name + self.version + ' 已激活')
            keyboard.add_hotkey(self.hotkey_start, self.timing_click)
        else:
            self.setWindowTitle(self.app_name + self.version + ' 未激活')
            keyboard.remove_hotkey(self.hotkey_start)

    def set_delay(self, delay):
        self.delay = delay

    def show_time(self, text):
        self.lbl_time.setText(text)
        self.lbl_time.adjustSize()

    def show_msg(self, text):
        self.lbl_msg.setText(text)
        self.lbl_msg.adjustSize()

    def timing_click(self):
        if not self.task_active:
            second = 10.0
            if len(str(self.lbl_time.text())) > 0:
                second = float(self.lbl_time.text())

            print('second', second)

            # for i in range(1):
            #     toast = '秒开始'
            #     self.show_time(str(1 - i))
            #     self.show_msg(toast)
            #     time.sleep(1)

            start = time.time()
            try:
                self.task_active = True
                # 创建子线程
                _thread.start_new_thread(self.timing_click_thread, (second, self.delay, start,))
                _thread.start_new_thread(self.toast, (second, start,))
            except Exception as e:
                print(f"Error: 任务开启失败, {e}")
        else:
            self.task_active = False

    def toast(self, second, start):
        end = start
        while (end - start) < second and self.task_active:
            print('toast')
            end = time.time()
            self.show_time(str(end - start)[0: 6])
            self.show_msg('秒,(' + str(second) + ')')
            time.sleep(1)

        self.show_time(str(second))
        self.show_msg('秒定时任务结束')

    def timing_click_thread(self, second, interval, start):
        end = start
        while (end - start) < second and self.task_active:
            end = time.time()
            print(end - start)
            mouse_click()
            print(float(interval))
            time.sleep(float(interval))
        self.init_params()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
